<script setup>
import { ref, onMounted } from 'vue'
import { TrendCharts, DataBoard, Connection, Grid, Document, FolderOpened, Timer } from '@element-plus/icons-vue'
import { getDashboardStats } from '../api/dashboard.js'
import { ElLoading } from 'element-plus'

const loading = ref(false)
const dashboardData = ref({})

const stats = ref([
  { title: 'API总数', key: 'totalApis', icon: Connection, color: '#409EFF' },
  { title: '应用数量', key: 'totalApps', icon: Grid, color: '#67C23A' },
  { title: '数据集', key: 'totalDatasets', icon: Document, color: '#E6A23C' },
  { title: '数据源', key: 'totalDatasources', icon: DataBoard, color: '#F56C6C' }
])

const callStats = ref([
  { title: '今日调用', key: 'todayCalls', icon: Timer, color: '#409EFF' },
  { title: '本周调用', key: 'weekCalls', icon: Timer, color: '#67C23A' },
  { title: '本月调用', key: 'monthCalls', icon: Timer, color: '#E6A23C' },
  { title: '总调用次数', key: 'totalCalls', icon: Timer, color: '#F56C6C' }
])

const quickActions = ref([
  { title: '新增API', icon: Connection, route: '/api/pageList', color: '#409EFF' },
  { title: '创建应用', icon: Grid, route: '/app/pageList', color: '#67C23A' },
  { title: '添加数据集', icon: Document, route: '/dataset/pageList', color: '#E6A23C' },
  { title: '配置数据源', icon: DataBoard, route: '/datasource/pageList', color: '#F56C6C' }
])

const systemInfo = ref([
  { label: '启用API', key: 'enabledApis', type: 'success' },
  { label: '停用API', key: 'disabledApis', type: 'warning' },
  { label: '可用数据源', key: 'availableDatasources', type: 'success' },
  { label: '不可用数据源', key: 'unavailableDatasources', type: 'danger' }
])

// 加载仪表盘数据
async function loadDashboardData() {
  loading.value = true
  try {
    const data = await getDashboardStats()
    if (data) {
      dashboardData.value = data
    }
  } catch (error) {
    console.error('加载仪表盘数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取统计值
function getStatValue(key) {
  if (!dashboardData.value.overallStats) return 0
  return dashboardData.value.overallStats[key] || 0
}

// 获取调用统计值
function getCallStatValue(key) {
  if (!dashboardData.value.apiCallStats) return 0
  return dashboardData.value.apiCallStats[key] || 0
}

// 获取API状态统计值
function getApiStatusValue(key) {
  if (!dashboardData.value.apiStatusStats) return 0
  return dashboardData.value.apiStatusStats[key] || 0
}

// 获取数据源状态统计值
function getDatasourceStatusValue(key) {
  if (!dashboardData.value.datasourceStatusStats) return 0
  return dashboardData.value.datasourceStatusStats[key] || 0
}

// 获取系统信息值
function getSystemInfoValue(key) {
  if (key === 'enabledApis' || key === 'disabledApis') {
    return getApiStatusValue(key)
  } else {
    return getDatasourceStatusValue(key)
  }
}

// 格式化数字显示
function formatNumber(num) {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + 'w'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k'
  }
  return num.toString()
}

onMounted(() => {
  loadDashboardData()
})
</script>

<template>
  <div class="dashboard" v-loading="loading">
    <div class="dashboard-header">
      <h2 class="dashboard-title">
        <el-icon><TrendCharts /></el-icon>
        仪表盘总览
      </h2>
      <p class="dashboard-subtitle">欢迎使用 All2API 管理平台</p>
    </div>

    <!-- 总体统计卡片 -->
    <div class="stats-grid">
      <el-card v-for="stat in stats" :key="stat.title" class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-left">
            <div class="stat-value">{{ formatNumber(getStatValue(stat.key)) }}</div>
            <div class="stat-title">{{ stat.title }}</div>
          </div>
          <div class="stat-right">
            <el-icon class="stat-icon" :style="{ color: stat.color }" size="48">
              <component :is="stat.icon" />
            </el-icon>
          </div>
        </div>
      </el-card>
    </div>

    <!-- API调用统计 -->
    <el-row style="margin-top: 24px;">
      <el-col :span="24">
        <el-card class="section-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>API调用统计</span>
            </div>
          </template>
          <div class="call-stats-grid">
            <div v-for="callStat in callStats" :key="callStat.title" class="call-stat-item">
              <div class="call-stat-icon" :style="{ color: callStat.color }">
                <el-icon size="24">
                  <component :is="callStat.icon" />
                </el-icon>
              </div>
              <div class="call-stat-info">
                <div class="call-stat-value">{{ formatNumber(getCallStatValue(callStat.key)) }}</div>
                <div class="call-stat-title">{{ callStat.title }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="24" style="margin-top: 24px;">
      <!-- 快速操作 -->
      <el-col :span="12">
        <el-card class="section-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>快速操作</span>
            </div>
          </template>
          <div class="quick-actions">
            <div 
              v-for="action in quickActions" 
              :key="action.title" 
              class="quick-action-item"
              @click="$router.push(action.route)"
            >
              <el-icon class="action-icon" :style="{ color: action.color }">
                <component :is="action.icon" />
              </el-icon>
              <span class="action-title">{{ action.title }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 最近API调用日志 -->
      <el-col :span="12">
        <el-card class="section-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最近API调用</span>
            </div>
          </template>
          <div class="recent-activities">
            <div v-if="!dashboardData.recentApiCalls || dashboardData.recentApiCalls.length === 0" class="empty-data">
              暂无调用记录
            </div>
            <div v-else>
              <div v-for="call in dashboardData.recentApiCalls" :key="call.businessId" class="activity-item">
                <div class="activity-time">{{ call.logTime?.split(' ')[1]?.substring(0, 5) || '--:--' }}</div>
                <div class="activity-content">
                  <el-tag type="success" size="small">{{ call.apiName || 'API调用' }}</el-tag>
                  <span class="activity-target">{{ call.appName || '--' }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 系统状态信息 -->
    <el-row style="margin-top: 24px;">
      <el-col :span="24">
        <el-card class="section-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>系统状态</span>
            </div>
          </template>
          <el-row :gutter="24">
            <el-col v-for="info in systemInfo" :key="info.label" :span="6">
              <div class="system-info-item">
                <div class="info-label">{{ info.label }}</div>
                <div class="info-value">
                  <el-tag :type="info.type">{{ getSystemInfoValue(info.key) }}</el-tag>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- API调用趋势图 -->
    <el-row v-if="dashboardData.apiTrendData && dashboardData.apiTrendData.length > 0" style="margin-top: 24px;">
      <el-col :span="24">
        <el-card class="section-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>API调用趋势（最近7天）</span>
            </div>
          </template>
          <div class="trend-chart">
            <div class="trend-items">
              <div v-for="trend in dashboardData.apiTrendData" :key="trend.date" class="trend-item">
                <div class="trend-date">{{ trend.date }}</div>
                <div class="trend-bar">
                  <div 
                    class="trend-fill" 
                    :style="{ 
                      height: Math.max(4, (trend.callCount / Math.max(...dashboardData.apiTrendData.map(t => t.callCount))) * 100) + '%' 
                    }"
                  ></div>
                </div>
                <div class="trend-value">{{ trend.callCount }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.dashboard {
  padding: 0;
}

.dashboard-header {
  margin-bottom: 32px;
}

.dashboard-title {
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
}

.dashboard-title .el-icon {
  margin-right: 12px;
  color: #667eea;
}

.dashboard-subtitle {
  font-size: 16px;
  color: #6c757d;
  margin: 0;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 12px;
  border: none;
  transition: transform 0.2s, box-shadow 0.2s;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0,0,0,0.1) !important;
}

.stat-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.stat-left {
  flex: 1;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-title {
  font-size: 14px;
  color: #6c757d;
  margin-bottom: 4px;
}

.stat-trend {
  font-size: 12px;
  font-weight: 600;
}

.stat-right {
  margin-left: 16px;
}

.stat-icon {
  opacity: 0.8;
}

.section-card {
  border-radius: 12px;
  border: none;
  height: 100%;
}

.card-header {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.quick-action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24px 16px;
  border-radius: 8px;
  background-color: #f8f9fa;
  cursor: pointer;
  transition: all 0.3s ease;
}

.quick-action-item:hover {
  background-color: #e9ecef;
  transform: translateY(-2px);
}

.action-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.action-title {
  font-size: 14px;
  font-weight: 500;
  color: #495057;
}

.recent-activities {
  max-height: 280px;
  overflow-y: auto;
}

.activity-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f1f3f4;
}

.activity-item:last-child {
  border-bottom: none;
}

.activity-time {
  font-size: 12px;
  color: #6c757d;
  width: 50px;
  flex-shrink: 0;
}

.activity-content {
  flex: 1;
  margin-left: 16px;
  display: flex;
  align-items: center;
}

.activity-target {
  margin-left: 8px;
  font-size: 14px;
  color: #495057;
}

.system-info-item {
  text-align: center;
  padding: 16px 0;
}

.info-label {
  font-size: 14px;
  color: #6c757d;
  margin-bottom: 8px;
}

.info-value {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

/* API调用统计样式 */
.call-stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 24px;
}

.call-stat-item {
  display: flex;
  align-items: center;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
  transition: background-color 0.3s ease;
}

.call-stat-item:hover {
  background-color: #e9ecef;
}

.call-stat-icon {
  margin-right: 12px;
}

.call-stat-info {
  flex: 1;
}

.call-stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
  line-height: 1;
  margin-bottom: 4px;
}

.call-stat-title {
  font-size: 14px;
  color: #6c757d;
}

/* 空数据样式 */
.empty-data {
  text-align: center;
  color: #6c757d;
  padding: 40px 20px;
  font-size: 14px;
}

/* 趋势图样式 */
.trend-chart {
  padding: 20px 0;
}

.trend-items {
  display: flex;
  justify-content: space-between;
  align-items: end;
  height: 120px;
  gap: 8px;
}

.trend-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100%;
}

.trend-date {
  font-size: 12px;
  color: #6c757d;
  margin-bottom: 8px;
}

.trend-bar {
  flex: 1;
  width: 20px;
  background-color: #f1f3f4;
  border-radius: 10px;
  position: relative;
  display: flex;
  align-items: end;
}

.trend-fill {
  width: 100%;
  background: linear-gradient(to top, #409EFF, #66b1ff);
  border-radius: 10px;
  min-height: 4px;
  transition: height 0.3s ease;
}

.trend-value {
  font-size: 12px;
  color: #2c3e50;
  font-weight: 600;
  margin-top: 8px;
}
</style>